package com.qububu.emporium.shoppingCart;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.qububu.utils.SystemConstants;

public class ShoppingCartInterceptor implements HandlerInterceptor {

	// 许访问的URL地址
//	private List<String> allowUrls;
//
//	public List<String> getAllowUrls() {
//		return allowUrls;
//	}
//
//	public void setAllowUrls(List<String> allowUrls) {
//		this.allowUrls = allowUrls;
//	}

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

//	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request, HttpServletResponse arg1,
			Object arg2) throws Exception {
		
		/*String uri = request.getRequestURI();
		for(String url : allowUrls) {
        	
            if(uri.endsWith(url)) {
            	HttpSession session = request.getSession();
                if (session.getAttribute(session.getId()) != null) {
                	if (((Map<String, Object>) session.getAttribute(session.getId())).size() > 0 ) {
                		return true;
                	} else {
                		return false;
                	}
                } else
                	return false;
            }
        }*/
		
		return cheak(request);
	}
	
	private boolean cheak(HttpServletRequest request) throws Exception {
		String cartKey = request.getHeader(SystemConstants.CART_IDENTIFICATION_KEY);
		if (! request.getSession().getAttribute(SystemConstants.CART_IDENTIFICATION_KEY).equals(cartKey)) {
			throw new Exception("找不到购物车");
		}
		
		return true;
	}
}
